package org.schat;

import com.alibaba.fastjson.JSONObject;
import org.schat.utils.RSAUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.Socket;

/**
 * @Description socket 数据处理线程
 * @Author lsh
 **/
public class SocketHandlerRunnable implements Runnable{
	private String clientId;

	public SocketHandlerRunnable(String clientId){
		this.clientId=clientId;
	}

	@Override
	public void run() {
		ClientDomain clientDoamin=IMServer.clientMap.get(clientId);
		if(clientDoamin !=null) {
			receiveClientMsg(clientDoamin);
		}
	}
	
	private void receiveClientMsg(ClientDomain clientDoamin){
		try {
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			Socket socket=clientDoamin.getSocket();
			InputStream is = socket.getInputStream();
			int b;
			while(check() && (b=is.read())!=-1){
				char c=(char)b;
				if(c !='\n') {
					out.write(b);
				}else {
					String data=new String(out.toByteArray());
                    JSONObject msgJson = (JSONObject)JSONObject.parse(data);
					String type = "";
					String msg = "";
                    if(msgJson !=null){
                    	type = (String)msgJson.get("type");
                    	msg = (String)msgJson.get("msg");
					}
                    if("0".equals(type)){
                        JSONObject jsonObject = new JSONObject();
                        //安全验证
                        if(clientDoamin.getAuthorization() == -1){
                            //判断安全验证是否成功
                            String decodedData = RSAUtils.privateDecrypt(msg, RSAUtils.getPrivateKey(Constant.CLIENT_PRIVATE_KEY));
                            if("hello world!".equals(decodedData)){
                                //成功 修改状态
                                clientDoamin.setAuthorization(2);
								long currentTime=System.currentTimeMillis();
								clientDoamin.setState(0);
								clientDoamin.setLastAcceptTime(currentTime);
								IMServer.clientMap.put(clientId, clientDoamin);
								//返回成功信息
								IMServer.sendMsgToClient(clientDoamin.getSocket(),"0","1000");
                                String success=clientDoamin.getClientInfo()+" 加入成功！";
                                System.out.println(success);
                            }else{
                                //失败 关闭连接
                                clientDoamin.setAuthorization(-999);
                                clientDoamin.closeSocket();
                                IMServer.removeClient(clientDoamin);
                                System.out.println(clientDoamin.getClientInfo()+" 权限校验失败，连接关闭");
                            }
                        }
                    }else{
                        //判断是否验证成功
                        if(clientDoamin.getAuthorization() ==2){
                            if ("1".equals(type)){
                                //群聊
                                IMServer.msgQue.offer(new MessageDomain("1",clientDoamin.getClientName()+":"+msg));
                                System.out.println("form "+clientDoamin.getClientInfo()+":"+msg);
                            }else if("2".equals(type)){
                                //保持心跳
                                long currentTime=System.currentTimeMillis();
                                clientDoamin.setState(0);
                                clientDoamin.setLastAcceptTime(currentTime);
                                IMServer.clientMap.put(clientId, clientDoamin);
                            }else if("3".equals(type)){
                            }else if("4".equals(type)){
								JSONObject thanosParameter = (JSONObject)JSONObject.parse(msg);
								boolean first = (boolean)thanosParameter.get("isFirst");
								//判断是否首次发起请求
								if(first){
									//返回Thanos的版本号
									JSONObject thanosRetInfo = new JSONObject();
									thanosRetInfo.put("resultCode","8888");
									thanosRetInfo.put("thanosVersion",Thanos.getThanosVersion()+"");
									IMServer.sendMsgToClient(clientDoamin.getSocket(),"4",thanosRetInfo.toJSONString());
								}else{
									//获得传过来的Thanos版本号
									String thanosVersion =(String)thanosParameter.get("thanosVersion");
									//发动灭霸的响指	,
									JSONObject thanosRetInfo = Thanos.snap(Long.valueOf(thanosVersion),clientDoamin);
									//消息返回给发动者（有可能发动者也被自己的响指给消灭掉了！！！）
									IMServer.sendMsgToClient(clientDoamin.getSocket(),"4",thanosRetInfo.toJSONString());
								}
							}
                        }else{
                            clientDoamin.closeSocket();
                            IMServer.removeClient(clientDoamin);
                            System.out.println(clientDoamin.getClientInfo()+" 警告！未授权的连接，连接即将关闭");
                        }
                    }
					out.reset();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean check() {
		ClientDomain clientDoamin=IMServer.clientMap.get(clientId);
		if(clientDoamin !=null && !clientDoamin.getSocket().isClosed()) {
			return true;
		}else {
			return false;
		}
	}

}
